package com.zhj.edu.utils;

public class SnowflakeIdGenerator {
    private final long workerId;
    private final long datacenterId;
    private long sequence;
    private final long epoch = 1585644268888L; // 自定义的起始时间戳
    private long lastTimestamp = -1L;

    public SnowflakeIdGenerator(long workerId, long datacenterId) {
        this.workerId = workerId;
        this.datacenterId = datacenterId;
        this.sequence = 0L;
    }

    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate id");
        }

        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & 0xFFF; // 4096
        } else {
            sequence = 0;
        }

        lastTimestamp = timestamp;

        return ((timestamp - epoch) << 22) | (datacenterId << 17) | (workerId << 12) | sequence;
    }
}